package net.looker.monitor.analyzer;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import net.looker.config.ConfigManager;
import net.looker.config.SiteConfig;
import net.looker.data.Category;
import net.looker.data.News;

/**
 * 新闻列表分析器
 * 分析出所有的新闻列表
 * @author solosky
 *
 */

public class CategoryAnalyzer extends Analyzer 
{
	/**
	 * 新闻对象数组
	 * 用于建立新闻对象
	 */
	private List<News> newsList;
	
	/**
	 * 栏目标题
	 */
	private Category category;
	
	/**
	 * 构造函数
	 * @param SiteConfig 站点配置
	 * @param List<News>
	 * @param Category
	 */
	public CategoryAnalyzer(String source, Category cate)
	{
		super(source,cate.getSiteConfig());
		newsList   = new ArrayList<News>();
		category   = cate; 
	}
	
	@Override
	public boolean analyze() {
		//建立提取标题和新闻ID的正则表达式
		Pattern pt = Pattern.compile(siteConfig.get("list.patterns.news"));
		Matcher mc = pt.matcher(source);
		News oneNews = null;
		String url = siteConfig.get("site.url")+siteConfig.get("view.index");
			//循环提取其中的新闻
			while (mc.find())
			{
				//建立新的新闻对象
				oneNews = new News();
				//新闻ID
				String newsID = mc.group(Integer.parseInt(siteConfig.get("list.group.newsid")));
				//新闻url
				oneNews.setUrl(url.replace("{newsid}",newsID ));
				//新闻锚文字
				oneNews.setAnchor(mc.group(Integer.parseInt(siteConfig.get("list.group.anchor"))));
				//新闻栏目地址
				oneNews.setCategory(category);
				//添加这条新闻至列表
				newsList.add(oneNews);
				//Logger.getLogger("looker").info("成功解析新闻:"+oneNews.toString());
			}
			return true;
	}
	
	/**
	 * 返回总共有多少页
	 * @return int 总共的页数
	 */
	public int getPageCnt()
	{
		Pattern pt = Pattern.compile(siteConfig.get("list.patterns.page"));
		Matcher mc = pt.matcher(source);
		if (mc.matches())
			return Integer.parseInt(mc.group(1));
		else
			return -1;
	}

	@Override
	public Object getAnalyzed()
	{
		return newsList;
	}

}
